<template>
  <div>
    <!--引用表格-->
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button type="primary" @click="handleAdd" preIcon="ant-design:plus-outlined"> 赠送消费积分</a-button>

        <a-dropdown v-if="selectedRowKeys.length > 0">
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="batchHandleDelete">
                <Icon icon="ant-design:delete-outlined"></Icon>
                删除
              </a-menu-item>
            </a-menu>
          </template>
          <a-button v-auth="'shipMerchantAmountLog2:ship_merchant_amount_log:deleteBatch'">批量操作
            <Icon icon="mdi:chevron-down"></Icon>
          </a-button>
        </a-dropdown>
        <!-- 高级查询 -->
        <!-- <super-query :config="superQueryConfig" @search="handleSuperQuery" /> -->
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)" />
      </template>
      <!--字段回显插槽-->
      <template v-slot:bodyCell="{ column, record, index, text }">
      </template>
    </BasicTable>
    <a-modal v-model:visible="visible" @ok="handleOk">
      <a-form :label-col="{ span: 4 }" :wrapper-col="{ span: 14 }" style="padding-top: 50px;">
        <!-- 判断是否2  有2了直接复制  否则下拉 -->
        <a-form-item label="商家">
          <a-input type="text" v-if="userInfo.userType == 2" disabled :value='addPointsInfo.merchantId' />
          <!-- <a-select :options="options" @change="handleChange" v-else v-model:value="addPointsInfo.merchantId">
          </a-select> -->

          <a-select show-search placeholder="请选择商家" option-filter-prop="label" :filter-option="filterOption"
            v-model:value="addPointsInfo.merchantId" v-else>
            <a-select-option v-for="user in options" :key="user.id" :value="user.id"
              :label="user.username + ' ' + user.phone">
              {{ user.realname }}
            </a-select-option>
          </a-select>

        </a-form-item>

        <a-form-item label="用户">
          <a-select show-search placeholder="请选择用户" option-filter-prop="label" :filter-option="filterOption"
            v-model:value="addPointsInfo.userId">
            <a-select-option v-for="user in userList" :key="user.id" :value="user.userId"
              :label="user.username + ' ' + user.phone">
              {{ user.realname }}
            </a-select-option>
          </a-select>
          <!-- <a-select v-model:value="addPointsInfo.phone" show-search :options="options1" @change="userHandleChange"
            :filter-option="true" :filter-option="filterUser">
          </a-select> -->
          <!-- <a-select :options="userList" @change="userHandleChange">
          </a-select> -->
        </a-form-item>
        <a-form-item label="赠送积分">
          <a-input type="number" v-model:value="addPointsInfo.point" />
        </a-form-item>

      </a-form>
    </a-modal>
    <!-- 表单区域 -->
    <ShipMerchantAmountLogModal @register="registerModal" @success="handleSuccess"></ShipMerchantAmountLogModal>
  </div>
</template>

<script lang="ts" name="shipMerchantAmountLog2-shipMerchantAmountLog" setup>
import { useMessage } from '/@/hooks/web/useMessage';
const { createMessage } = useMessage();

import { ref, reactive, computed, unref, onMounted } from 'vue';
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { useModal } from '/@/components/Modal';
import { useListPage } from '/@/hooks/system/useListPage'
import ShipMerchantAmountLogModal from './components/ShipMerchantAmountLogModal.vue'
import { columns, searchFormSchema, superQuerySchema } from './ShipMerchantAmountLog.data';
import { list, deleteOne, batchDelete, getImportUrl, getExportUrl, getShopList, getuserList, addPoint, refundMemberPoints } from './ShipMerchantAmountLog.api';

import { downloadFile } from '/@/utils/common/renderUtils';
import { useUserStore } from '/@/store/modules/user';
import { object } from 'vue-types';
onMounted(() => {
  getShop()
  getUser()
})
const options1 = ref<SelectTypes['options']>([

]);
const queryParam = reactive<any>({});
const checkedKeys = ref<Array<string | number>>([]);
const userStore = useUserStore();
//注册model
const [registerModal, { openModal }] = useModal();
//注册table数据
const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
  tableProps: {
    title: 'ship_merchant_amount_log',
    api: list,
    columns,
    canResize: false,
    formConfig: {
      //labelWidth: 120,
      schemas: searchFormSchema,
      autoSubmitOnEnter: true,
      showAdvancedButton: true,
      fieldMapToNumber: [
      ],
      fieldMapToTime: [
      ],
    },
    actionColumn: {
      width: 120,
      fixed: 'right'
    },
    beforeFetch: (params) => {
      return Object.assign(params, queryParam);
    },
  },
  exportConfig: {
    name: "ship_merchant_amount_log",
    url: getExportUrl,
    params: queryParam,
  },
  importConfig: {
    url: getImportUrl,
    success: handleSuccess
  },
})

const [registerTable, { reload }, { rowSelection, selectedRowKeys }] = tableContext
const visible = ref<boolean>(false);

const userInfo = reactive({})
const addPointsInfo = reactive({
  merchantId: '',
  phone: '',
  point: '',
  id: '',
  userId: ''

})
const options = ref();
const userList = ref();
// 高级查询配置
const superQueryConfig = reactive(superQuerySchema);
// 获取商家列表
const getShop = () => {
  getShopList({
    userType: 2,
    pageSize: 99
  }).then((res) => {
    if (res) {

      options.value = res.records.filter(user => user.id !== JSON.parse(localStorage.getItem('userInfo')).id);




      // options.value.forEach(element => {

      //   element.label = element.realname
      //   element.value = element.id
      // });
    }
  })
}
const filterOption = (input, option) => {
  const label = option.label.toLowerCase();

  return label.includes(input.toLowerCase());
};
const array = ref()
//获取用户列表
const getUser = () => {
  getuserList({ userType: 1, pageSize: 99 }).then((res) => {
    if (res) {
      array.value = [...res.records, ...options.value]


      userList.value = array.value.filter(user => user.id !== JSON.parse(localStorage.getItem('userInfo')).id);

      // userList.value.forEach(element => {
      //   options1.value.push({
      //     label: element.realname,
      //     value: element.phone,
      //   })
      // });
    }
  })
}
// 选择用户
const userHandleChange = (e) => {
  addPointsInfo.phone = e;
};
// 选择商家
const handleChange = (value: string) => {
  addPointsInfo.merchantId = value;
};
/**
 * 高级查询事件
 */
function handleSuperQuery(params) {
  Object.keys(params).map((k) => {
    queryParam[k] = params[k];
  });
  reload();
}
const handleOk = () => {



  if (!addPointsInfo.merchantId) {
    createMessage.warning('请选择商家');
    return
  }
  if (!addPointsInfo.userId) {
    createMessage.warning('请选择用户');

    return

  }
  if (!addPointsInfo.point) {
    createMessage.warning('请输入积分');
    return

  }
  addPoint(addPointsInfo).then(res => {
    addPointsInfo.point = ''
    addPointsInfo.merchantId = ''
    addPointsInfo.phone = ''
    addPointsInfo.userId = ''
    visible.value = false;
    reload();
  })
};
const refundMemberPointsMethod = (e) => {

  refundMemberPoints({
    id: e.id
  }).then(res => {
    reload();

  })
}
/**
 * 新增事件
 */
function handleAdd() {
  visible.value = true;
  Object.assign(userInfo, JSON.parse(localStorage.getItem('userInfo')))
  if (userInfo.userType == 2) {
    addPointsInfo.merchantId = userInfo.id
  }
}

/**
 * 编辑事件
 */
function handleEdit(record: Recordable) {
  openModal(true, {
    record,
    isUpdate: true,
    showFooter: true,
  });
}
/**
 * 详情
*/
function handleDetail(record: Recordable) {
  openModal(true, {
    record,
    isUpdate: true,
    showFooter: false,
  });
}
/**
 * 删除事件
 */
async function handleDelete(record) {
  await deleteOne({ id: record.id }, handleSuccess);
}
/**
 * 批量删除事件
 */
async function batchHandleDelete() {
  await batchDelete({ ids: selectedRowKeys.value }, handleSuccess);
}
/**
 * 成功回调
 */
function handleSuccess() {
  (selectedRowKeys.value = []) && reload();
}
/**
   * 操作栏
   */
function getTableAction(record) {
  if (!record.isRefund) {
    return [
      {
        label: '编辑',
        onClick: handleEdit.bind(null, record)

      }
    ]
  } else {
    return [{
      label: '回退',
      popConfirm: {
        title: '是否确认回退',
        confirm: refundMemberPointsMethod.bind(null, record),
      }

    },
    {
      label: '编辑',
      onClick: handleEdit.bind(null, record)

    }
    ]
  }

}
/**
   * 下拉操作栏
   */
function getDropDownAction(record) {
  return [
    // {
    //   label: '详情',
    //   onClick: handleDetail.bind(null, record),
    // }, {
    //   label: '删除',
    //   popConfirm: {
    //     title: '是否确认删除',
    //     confirm: handleDelete.bind(null, record),
    //     placement: 'topLeft',
    //   },

    // }
  ]
}



</script>

<style lang="less" scoped>
:deep(.ant-picker),
:deep(.ant-input-number) {
  width: 100%;
}
</style>